//
//  PKRequestManager.m
//  AWhile
//
//  Created by lanou on 15/9/26.
//  Copyright (c) 2015年 陈文杰. All rights reserved.
//

#import "PKRequestManager.h"

@implementation PKRequestManager

- (void)requestWithType:(RequsetType)type urlString:(NSString *)urlString parDic:(NSDictionary *)parDic finish:(RequestFinish)finish error:(RequestError)error{
    
    // 拿到参数之后进行请求
    NSURL *url = [NSURL URLWithString:urlString];
    // 创建可变的URLRequest
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    // 如果请求方式是POST需要设置参数和请求方式
    if (type == POST) {
        // 设置请求方式
        [request setHTTPMethod:@"POST"];
        if (parDic.count > 0) {
            // 设置请求参数的Body体
            [request setHTTPBody:[self parDicToPataWithDic:parDic]];
        }
    }
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (data) {
            finish(data);
        }
        else{
            error(connectionError);
        }
    }];
}

+ (void)requestWithType:(RequsetType)type urlString:(NSString *)urlString parDic:(NSDictionary *)parDic finish:(RequestFinish)finish error:(RequestError)error{
    
    PKRequestManager *manager = [[PKRequestManager alloc] init];
    [manager requestWithType:type urlString:urlString parDic:parDic finish:finish error:error];
}

// 把参数字典转为POST请求所需要的参数体
- (NSData *)parDicToPataWithDic:(NSDictionary *)dic{
    NSMutableArray *array = [NSMutableArray array];
    // 遍历字典得到每一个键,得到所有的 key = value 类型的字符串
    for (NSString *key in dic) {
        NSString *str = [NSString stringWithFormat:@"%@=%@", key, dic[key]];
        [array addObject:str];
    }
    // 数组里所有key = value的字符串通过&符号连接
    NSString *parString = [array componentsJoinedByString:@"&"];
    return [parString dataUsingEncoding:NSUTF8StringEncoding];
}

@end
